home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10079 < prev    next >
Encoding:
Text File  |  1996-08-05  |  42.2 KB  |  1,039 lines

  1. Path: sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #2/4
  5. Followup-To: comp.lang.c++
  6. Date: 6 Mar 1996 02:21:10 GMT
  7. Organization: Paradigm Shift, Inc (technology consulting)
  8. Sender: cline@sun.soe.clarkson.edu
  9. Distribution: world
  10. Expires: +1 month
  11. Message-ID: <4hisqm$hfk@library.erc.clarkson.edu>
  12. Reply-To: cline@parashift.com (Marshall Cline)
  13. NNTP-Posting-Host: sun.soe.clarkson.edu
  14. Summary: Please read this before posting to comp.lang.c++
  15. Archive-name: C++-faq/part2_4
  16.  
  17. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  18. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  19. Posting 2 of 4.
  20. Posting #1 explains copying permissions, (no)warranty, table-of-contents, etc
  21.  
  22. ==============================================================================
  23. SECTION 9: Freestore management
  24. ==============================================================================
  25.  
  26. Q37: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  27.  
  28. The pointed-to-data.
  29.  
  30. "delete" really means "delete the thing pointed to by."  The same abuse of
  31. English occurs when "free"ing the memory pointed to by a ptr in C ("free(p)"
  32. really means "free_the_stuff_pointed_to_by(p)").
  33.  
  34. ==============================================================================
  35.  
  36. Q38: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  37.    alloc'd with "malloc()"?
  38.  
  39. NO!
  40.  
  41. It is perfectly legal, moral, and wholesome to use malloc/free and new/delete
  42. in the same program, but it is illegal, immoral, and despicable to 'free' a
  43. pointer allocated via 'new', or to 'delete' a pointer allocated via 'malloc'.
  44.  
  45. BEWARE!  I occasionally get email from people telling me that it works ok for
  46. them on machine X and compiler Y.  I don't care if you're just working with an
  47. array of char; do NOT do this!  If you allocated via 'p = new char[n]', you
  48. MUST use 'delete[] p'.  You must NOT use 'delete p', nor 'free(p)'.  Both these
  49. could fail if the code was ported to a new machine, a new compiler, or even a
  50. new version of the same compiler.
  51.  
  52. You have been warned.
  53.  
  54. ==============================================================================
  55.  
  56. Q39: Why should I use "new" instead of trustworthy old malloc()?
  57.  
  58. Constructors/destructors, type safety, overridability.
  59.  
  60. Constructors/destructors: unlike "malloc(sizeof(Fred))", "new Fred()" calls
  61. Fred's constructor.  Similarly, "delete p" calls "*p"'s destructor.
  62.  
  63. Type safety: malloc() returns a "void*" which isn't type safe.  "new Fred()"
  64. returns a ptr of the right type (a "Fred*").
  65.  
  66. Overridability: "new" is an operator that can be overridden by a class, while
  67. "malloc" is not overridable on a per-class basis.
  68.  
  69. ==============================================================================
  70.  
  71. Q40: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  72.  
  73. To save you from disaster.
  74.  
  75. When realloc() has to copy the allocation, it uses a BITWISE copy operation,
  76. which will tear most C++ objects to shreds.  C++ objects should be allowed to
  77. copy themselves: they use their own copy constructor or assignment operator.
  78.  
  79. ==============================================================================
  80.  
  81. Q41: How do I allocate / unallocate an array of things?
  82.  
  83. Use new[] and delete[]:
  84.  
  85.     Fred* p = new Fred[100];
  86.     //...
  87.     delete [] p;
  88.  
  89. Any time you use the "[...]" in the "new" expression, you *!*MUST*!* use "[]"
  90. in the "delete" statement.  This syntax is necessary because there is no
  91. syntactic difference between a pointer to a thing and a pointer to an array of
  92. things (something we inherited from C).
  93.  
  94. ==============================================================================
  95.  
  96. Q42: What if I forget the "[]" when "delete"ing array allocated via "new
  97.    Fred[n]"?
  98.  
  99. All life comes to a catastrophic end.
  100.  
  101. It is the programmer's --not the compiler's-- responsibility to get the
  102. connection between new[] and delete[] correct.  If you get it wrong, neither a
  103. compile-time nor a run-time error message will be generated by the compiler.
  104. Heap corruption is a likely result.  Or worse.  Your program will probably die.
  105.  
  106. ==============================================================================
  107.  
  108. Q43: Is it legal (and moral) for a member function to say "delete this"?
  109.  
  110. As long as you're careful, you'll be ok.
  111.  
  112. Here's how I define "careful":
  113. 1) You're absolutely 100% positive sure that "this" was allocated via "new"
  114.    (not by "new[]", nor by placement "new", by by plain ordinary "new").
  115. 2) You're absolutely 100% positive sure that your member function will be
  116.    the last member function invoked on this object.
  117. 3) After you do the suicide thing ("delete this;"), you must not touch any
  118.    piece of "this" object, including data or methods.
  119. 4) After you do the suicide thing ("delete this;"), you must not touch the
  120.    "this" pointer.  In other words, you must not examine it, compare it with
  121.    another pointer or with NULL, print it, cast it, do anything with it.
  122.  
  123. Naturally the usual caveats apply in cases where your "this" pointer is a
  124. pointer to a base class and the destructor isn't virtual.
  125.  
  126. ==============================================================================
  127.  
  128. Q44: How do I allocate multidimensional arrays using new?
  129.  
  130. There are many ways to do this, depending on how flexible you want the array
  131. sizing to be.  On one extreme, if you know all the dimensions at compile-time,
  132. you can allocate multidimensional arrays statically (as in C):
  133.  
  134.     class Fred { /*...*/ };
  135.  
  136.     void manipulateArray()
  137.     {
  138.       Fred matrix[10][20];
  139.  
  140.       //use matrix[i][j]...
  141.  
  142.       //no need for explicit deallocation
  143.     }
  144.  
  145. On the other extreme, if you want to allow the various slices of the matrix to
  146. have a different sizes, you can allocate everything off the freestore:
  147.  
  148.     void manipulateArray(unsigned nrows, unsigned ncols[])
  149.     //'nrows' is the number of rows in the array.
  150.     //therefore valid row numbers are from 0 to nrows-1 inclusive.
  151.     //'ncols[r]' is the number of columns in row 'r' ('r' in [0..nrows-1]).
  152.     {
  153.       Fred** matrix = new Fred*[nrows];
  154.       for (unsigned r = 0; r < nrows; ++r)
  155.         matrix[r] = new Fred[ ncols[r] ];
  156.  
  157.       //use matrix[i][j]...
  158.  
  159.       //deletion is the opposite of allocation:
  160.       for (r = nrows; r > 0; --r)
  161.         delete [] matrix[r-1];
  162.       delete [] matrix;
  163.     }
  164.  
  165. ==============================================================================
  166.  
  167. Q45: Does C++ have arrays whose length can be specified at run-time?
  168.  
  169. Yes, in the sense that STL has a vector template that provides this behavior.
  170. See on "STL" in the "Libraries" section.
  171.  
  172. No, in the sense that built-in array types need to have their length specified
  173. at compile time.
  174.  
  175. Yes, in the sense that even built-in array types can specify the first index
  176. bounds at run-time.  E.g., comparing with the previous FAQ, if you only need
  177. the first array dimension to vary, then you can just ask new for an array of
  178. arrays (rather than an array of pointers to arrays):
  179.  
  180.     const unsigned ncols = 100;
  181.     //'ncols' is not a run-time variable (number of columns in the array)
  182.  
  183.     class Fred { /*...*/ };
  184.  
  185.     void manipulateArray(unsigned nrows)
  186.     //'nrows' is a run-time variable (number of rows in the array)
  187.     {
  188.       Fred (*matrix)[ncols] = new Fred[nrows][ncols];
  189.  
  190.       //use matrix[i][j]
  191.  
  192.       //deletion is the opposite of allocation:
  193.       delete [] matrix;
  194.     }
  195.  
  196. You can't do this if you need anything other than the first dimension
  197. of the array to change at run-time.
  198.  
  199. ==============================================================================
  200.  
  201. Q46: How can I ensure objects of my class are always created via "new" rather
  202.    than as locals or global/static objects?
  203.  
  204. Make sure the class's constructors are "private:", and define "friend" or
  205. "static" fns that return a ptr to the objects created via "new" (make the
  206. constructors "protected:" if you want to allow derived classes).
  207.  
  208.     class Fred {    //only want to allow dynamicly allocated Fred's
  209.     public:
  210.       static Fred* create()                 { return new Fred();     }
  211.       static Fred* create(int i)            { return new Fred(i);    }
  212.       static Fred* create(const Fred& fred) { return new Fred(fred); }
  213.       virtual ~Fred();
  214.     private:
  215.       Fred();
  216.       Fred(int i);
  217.       Fred(const Fred& fred);
  218.     };
  219.  
  220.     main()
  221.     {
  222.       Fred* p = Fred::create(5);
  223.       //...
  224.       delete p;
  225.     }
  226.  
  227. ==============================================================================
  228. SECTION 10: Debugging and error handling
  229. ==============================================================================
  230.  
  231. Q47: How can I handle a constructor that fails?
  232.  
  233. Throw an exception.
  234.  
  235. Constructors don't have a return type, so it's not possible to use error codes.
  236. The best way to signal constructor failure is therefore to throw an exception.
  237.  
  238. Before C++ had exceptions, we signaled constructor failure by putting the
  239. object into a "half baked" state (e.g., by setting an internal status bit).
  240. There was a query ("inspector") method to check this bit, that allowed clients
  241. to discover whether they had a live object.  Other member functions would also
  242. check this bit, and, if the object wasn't really alive, do a no-op (or perhaps
  243. something more obnoxious such as "abort()").  This was really ugly.
  244.  
  245. ==============================================================================
  246.  
  247. Q48: How should I handle resources if my constructors may throw exceptions?
  248.  
  249. Every data member inside your object should clean up its own mess.
  250.  
  251. If a constructor throws an exception, the object's destructor is NOT run.  If
  252. your object has already done something that needs to be undone (such as
  253. allocating some memory, opening a file, or locking a semaphore), this "stuff
  254. that needs to be undone" MUST be remembered by a data member inside the object.
  255.  
  256. For example, rather than allocating memory into a raw "Fred*" data member, put
  257. the allocated memory into a "smart pointer" member object, and the destructor
  258. of this smart pointer will delete the Fred object when the smart pointer dies.
  259.  
  260. ==============================================================================
  261. SECTION 11: Const correctness
  262. ==============================================================================
  263.  
  264. Q49: What is "const correctness"?
  265.  
  266. A good thing.
  267.  
  268. Const correctness uses the keyword "const" to ensure const objects don't get
  269. mutated.  E.g., if function "f()" accepts a "String", and "f()" wants to
  270. promise not to change the "String", you:
  271.  
  272.  * can either pass by value:    void  f(      String  s   )  { /*...*/ }
  273.  * or by constant reference:    void  f(const String& s   )  { /*...*/ }
  274.  * or by constant pointer:    void  f(const String* sptr)  { /*...*/ }
  275.  * but NOT by non-const ref:    void  f(      String& s   )  { /*...*/ }
  276.  * NOR by non-const pointer:    void  f(      String* sptr)  { /*...*/ }
  277.  
  278. Attempted changes to "s" within a fn that takes a "const String&" are flagged
  279. as compile-time errors; neither run-time space nor speed is degraded.
  280.  
  281. Declaring the "constness" of a parameter is just another form of type safety.
  282. It is almost as if a constant String, for example, "lost" its various mutative
  283. operations.  If you find type safety helps you get systems correct (it does;
  284. especially in large systems), you'll find const correctness helps also.
  285.  
  286. ==============================================================================
  287.  
  288. Q50: Should I try to get things const correct "sooner" or "later"?
  289.  
  290. At the very, very, VERY beginning.
  291.  
  292. Back-patching const correctness results in a snowball effect: every "const" you
  293. add "over here" requires four more to be added "over there."
  294.  
  295. ==============================================================================
  296.  
  297. Q51: What is a "const member function"?
  298.  
  299. A member function that inspects (rather than mutates) its object.
  300.  
  301.     class Fred {
  302.     public:
  303.       void f() const;
  304.     };      // ^^^^^--- this implies "fred.f()" won't change "fred"
  305.  
  306. This means that the ABSTRACT (client-visible) state of the object isn't going
  307. to change (as opposed to promising that the "raw bits of the object's struct
  308. aren't going to change).  C++ compilers aren't allowed to take the "bitwise"
  309. interpretation, since a non-const alias could exist which could modify the
  310. state of the object (gluing a "const" ptr to an object doesn't promise the
  311. object won't change; it promises only that the object won't change VIA THAT
  312. POINTER).
  313.  
  314. "const" member functions are often called "inspectors."  Non-"const" member
  315. functions are often called "mutators."
  316.  
  317. ==============================================================================
  318.  
  319. Q52: What do I do if I want to update an "invisible" data member inside a
  320.    "const" member function?
  321.  
  322. Use "mutable", or use "const_cast".
  323.  
  324. A small percentage of inspectors need to make innocuous changes to data members
  325. (e.g., a "Set" object might want to cache its last lookup in hopes of improving
  326. the performance of its next lookup).  By saying the changes are "inocuous," I
  327. mean that the changes wouldn't be visible from outside the object's interface
  328. (otherwise the method would be a mutator rather than an inspector).
  329.  
  330. When this happens, the data member which will be modified should be marked as
  331. "mutable" (put the "mutable" keyword just before the data member's declaration;
  332. i.e., in the same place where you could put "const").  This tells the compiler
  333. that the data member is allowed to change during a const member function.  If
  334. you can't use "mutable", you can cast away the constness of "this" via
  335. "const_cast".  E.g., in "Set::lookup() const", you might say,
  336.  
  337.     Set* self = const_cast<Set*>(this);
  338.  
  339. After this line, "self" will have the same bits as "this" (e.g., "self==this"),
  340. but "self" is a "Set*" rather than a "const Set*".  Therefore you can use
  341. "self" to modify the object pointed to by "this".
  342.  
  343. ==============================================================================
  344.  
  345. Q53: Does "const_cast" mean lost optimization opportunities?
  346.  
  347. In theory, yes; in practice, no.
  348.  
  349. Even if a compiler outlawed "const_cast", the only way to avoid flushing the
  350. register cache across a "const" member function call would be to ensure that
  351. there are no non-const pointers that alias the object.  This can happen only in
  352. rare cases (when the object is constructed in the scope of the const member fn
  353. invocation, and when all the non-const member function invocations between the
  354. object's construction and the const member fn invocation are statically bound,
  355. and when every one of these invocations is also "inline"d, and when the
  356. constructor itself is "inline"d, and when any member fns the constructor calls
  357. are inline).
  358.  
  359. ==============================================================================
  360. SECTION 12: Inheritance
  361. ==============================================================================
  362.  
  363. Q54: Is inheritance important to C++?
  364.  
  365. Yep.
  366.  
  367. Inheritance is what separates abstract data type (ADT) programming from OOP.
  368.  
  369. ==============================================================================
  370.  
  371. Q55: When would I use inheritance?
  372.  
  373. As a specification device.
  374.  
  375. Human beings abstract things on two dimensions: part-of and kind-of.  A Ford
  376. Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc.  The
  377. part-of hierarchy has been a part of software since the ADT style became
  378. relevant; inheritance adds "the other" major dimension of decomposition.
  379.  
  380. ==============================================================================
  381.  
  382. Q56: How do you express inheritance in C++?
  383.  
  384. By the ": public" syntax:
  385.  
  386.     class Car : public Vehicle {
  387.             //^^^^^^^^---- ": public" is pronounced "is-a-kind-of-a'
  388.       //...
  389.     };
  390.  
  391. We state the above relationship in several ways:
  392.  * Car is "a kind of a" Vehicle
  393.  * Car is "derived from" Vehicle
  394.  * Car is "a specialized" Vehicle
  395.  * Car is the "subclass" of Vehicle
  396.  * Vehicle is the "base class" of Car
  397.  * Vehicle is the "superclass" of Car (this not as common in the C++ community)
  398.  
  399. ==============================================================================
  400.  
  401. Q57: Is it ok to convert a pointer from a derived class to its base class?
  402.  
  403. Yes.
  404.  
  405. A derived class is a specialized version of the base class ("Derived is a
  406. kind-of Base").  The upward conversion is perfectly safe, and happens all the
  407. time (if I am pointing at a car, I am in fact pointing at a vehicle):
  408.  
  409.     void f(Vehicle* v);
  410.     void g(Car* c) { f(c); }    //perfectly safe; no cast
  411.  
  412. Note that the answer to this FAQ assumes we're talking about "public"
  413. inheritance; see below on "private/protected" inheritance for "the other kind".
  414.  
  415. ==============================================================================
  416.  
  417. Q58: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  418.  
  419. C++ allows a Derived* to be converted to a Base*, since a Derived object is a
  420. kind of a Base object.  However trying to convert a Derived** to a Base** is
  421. (correctly) flagged as an error (if it was allowed, the Base** could be
  422. dereferenced (yielding a Base*), and the Base* could be made to point to an
  423. object of a DIFFERENT derived class.  This would be an error.
  424.  
  425. As a corollary, an array of Deriveds is-NOT-a-kind-of array of Bases.  At
  426. Paradigm Shift, Inc. we use the following example in our C++ training sessions:
  427.  
  428.                "A bag of apples is NOT a bag of fruit".
  429.  
  430. If a bag of apples COULD be passed as a bag of fruit, someone could put a
  431. banana into the bag of apples!
  432.  
  433. ==============================================================================
  434.  
  435. Q59: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  436.    bad?
  437.  
  438. Yes, "arrays are evil" (jest kidd'n :-).
  439.  
  440. There's a very subtle problem with using raw built-in arrays.  Consider this:
  441.  
  442.     void f(Base* arrayOfBase)
  443.     {
  444.       arrayOfBase[3].memberfn();
  445.     }
  446.  
  447.     main()
  448.     {
  449.       Derived arrayOfDerived[10];
  450.       f(arrayOfDerived);
  451.     }
  452.  
  453. The compiler thinks this is perfectly type-safe, since it can convert a
  454. Derived* to a Base*.  But in reality it is horrendously evil: since Derived
  455. might be larger than Base, the array index in f() not only isn't type safe, it
  456. may not even be pointing at a real object!  In general it'll be pointing
  457. somewhere into the innards of some poor Derived.
  458.  
  459. The root problem is that C++ can't distinguish between a ptr-to-a-thing and a
  460. ptr-to-an-array-of-things.  Naturally C++ "inherited" this feature from C.
  461.  
  462. NOTE: if we had used an array-like CLASS instead of using a raw array (e.g., an
  463. "Array<T>" rather than a "T[]"), this problem would have been properly trapped
  464. as an error at compile time rather than at run-time.
  465.  
  466. ==============================================================================
  467. SUBSECTION 12A: Inheritance -- Virtual functions
  468. ==============================================================================
  469.  
  470. Q60: What is a "virtual member function"?
  471.  
  472. A virtual function allows derived classes to replace the implementation
  473. provided by the base class.  The compiler ensures the replacement is always
  474. called whenever the object in question is actually of the derived class, even
  475. if the object is accessed by a base pointer rather than a derived pointer.
  476. This allows algorithms in the base class to be replaced in the derived class,
  477. even if users don't know about the derived class.
  478.  
  479. Note: the derived class can partially replace ("override") the base class
  480. method (the derived class method can invoke the base class version if desired).
  481.  
  482. ==============================================================================
  483.  
  484. Q61: How can C++ achieve dynamic binding yet also static typing?
  485.  
  486. In the following discussion, "ptr" means either a pointer or a reference.
  487.  
  488. When you have a ptr, there are two types: the (static) type of the ptr, and the
  489. (dynamic) type of the pointed-to object (the object may actually be of a class
  490. that is derived from the class of the ptr).
  491.  
  492. "Static typing" means that the "legality" of the call is checked based on the
  493. static type of the ptr: if the type of the ptr can handle the member fn,
  494. certainly the pointed-to object can handle it as well.
  495.  
  496. "Dynamic binding" means that the "code" that is called is based on the dynamic
  497. type of the pointed-to object.  This is called "dynamic binding," since the
  498. actual code being called is determined dynamically (at run time).
  499.  
  500. ==============================================================================
  501.  
  502. Q62: Should a derived class replace ("override") a non-virtual fn from a base
  503.    class?
  504.  
  505. It's legal, but it ain't moral.
  506.  
  507. Experienced C++ programmers will sometimes redefine a non-virtual fn for
  508. efficiency (the alternate implementation might make better use of the derived
  509. class' resources), or to get around the hiding rule (see below, and ARM
  510. ["Annotated Reference Manual"] sect.13.1).  However the client-visible effects
  511. must be IDENTICAL, since non-virtual fns are dispatched based on the static
  512. type of the ptr/ref rather than the dynamic type of the pointed-to/referenced
  513. object.
  514.  
  515. ==============================================================================
  516.  
  517. Q63: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  518.  
  519. It means you're going to die.
  520.  
  521. Here's the mess you're in: if Derived declares a member function named "f", and
  522. Base declares a member function named "f" with a different signature (e.g.,
  523. different parameter types and/or constness), then the Base "f" is "hidden"
  524. rather than "overloaded" or "overridden" (even if the Base "f" is virtual).
  525.  
  526. Here's how you get out of the mess: Derived must redefine the Base member
  527. function(s) that are hidden (even if they are non-virtual).  Normally this
  528. re-definition merely calls the appropriate Base member function.  E.g.,
  529.  
  530.     class Base {
  531.     public:
  532.       void f(int);
  533.     };
  534.  
  535.     class Derived : public Base {
  536.     public:
  537.       void f(double);
  538.       void f(int i) { Base::f(i); }
  539.     };             // ^^^^^^^^^^--- redefinition merely calls Base::f(int)
  540.  
  541. ==============================================================================
  542. SUBSECTION 12B: Inheritance -- Conformance
  543. ==============================================================================
  544.  
  545. Q64: Should I hide public member fns inherited from my base class?
  546.  
  547. Never, never, never do this.  Never.  NEVER!
  548.  
  549. Attempting to hide (eliminate, revoke) inherited public member functions is an
  550. all-too-common design error.  It usually stems from muddy thinking.
  551.  
  552. ==============================================================================
  553.  
  554. Q65: Is a "Circle" a kind-of an "Ellipse"?
  555.  
  556. Not if Ellipse promises to be able to change its size asymmetrically.
  557.  
  558. For example, suppose Ellipse has a "setSize(x,y)" method, and suppose this
  559. method promises "the Ellipse's width() will be x, and its height() will be y".
  560. In this case, Circle can't be a kind-of Ellipse.  Simply put, if Ellipse can do
  561. something Circle can't, then Circle can't be a kind of Ellipse.
  562.  
  563. This leaves two potential (valid) relationships between Circle and Ellipse:
  564.  * Make Circle and Ellipse completely unrelated classes.
  565.  * Derive Circle and Ellipse from a base class representing "Ellipses that
  566.    can't NECESSARILY perform an unequal-setSize operation."
  567.  
  568. In the first case, Ellipse could be derived from class "AsymmetricShape" (with
  569. setSize(x,y) being introduced in AsymmetricShape), and Circle could be derived
  570. from "SymmetricShape," which has a setSize(size) member fn.
  571.  
  572. In the second case, class "Oval" could only have "setSize(size)" which sets
  573. both the "width()" and the "height()" to "size", then derive both Ellipse and
  574. Circle from Oval.  Ellipse --but not Circle-- adds the "setSize(x,y)" operation
  575. (see the "hiding rule" for a caveat if the same method name "setSize()" is used
  576. for both operations).
  577.  
  578. ==============================================================================
  579.  
  580. Q66: Are there other options to the "Circle is/isnot kind-of Ellipse"
  581.    dilemma?
  582.  
  583. If you claim that all Ellipses can be squashed asymmetrically, and you claim
  584. that Circle is a kind-of Ellipse, and you claim that Circle can't be squashed
  585. asymmetrically, clearly you've got to adjust (revoke, actually) one of your
  586. claims.  Thus you've either got to get rid of "Ellipse::setSize(x,y)", get rid
  587. of the inheritance relationship between Circle and Ellipse, or admit that your
  588. "Circle"s aren't necessarily circular.
  589.  
  590. Here are the two most common traps new OO/C++ programmers regularly fall into.
  591. They attempt to use coding hacks to cover up a broken design (they redefine
  592. Circle::setSize(x,y) to throw an exception, call "abort()", or choose the
  593. average of the two parameters, or to be a no-op).  Unfortunately all these
  594. hacks will surprise users, since users are expecting "width() == x" and
  595. "height() == y".
  596.  
  597. The only rational way out of this would be to weaken the promise made by
  598. Ellipse's "setSize(x,y)" (e.g., you'd have to change it to, "This method MIGHT
  599. set width() to x and height() to y, or it might do NOTHING").  Unfortunately
  600. this dilutes the contract into dribble, since the user can't rely on any
  601. meaningful behavior.  The whole hierarchy therefore begins to be worthless
  602. (it's hard to convince someone to use an object if you have to shrug your
  603. shoulders when asked what the object does for them).
  604.  
  605. ==============================================================================
  606.  
  607. Q67: But I have a Ph.D. in Mathematics, and I'm SURE a Circle is a kind of an
  608.    Ellipse!  Does this mean Marshall Cline is stupid?  Or that C++ is stupid?  Or
  609.    that OO is stupid?
  610.  
  611. Actually, it doesn't mean any of these things.
  612.  
  613. Look, I have received and answered dozens of passionate email messages about
  614. this subject.  I have taught it hundreds of times to thousands of software
  615. professionals all over the place.  I know this goes against your intuition.
  616. But trust me; your intuition is just plain wrong.
  617.  
  618. The real problem is your intuitive notion of "kind of" doesn't match the OO
  619. notion of proper inheritance (technically called "subtyping").  The bottom line
  620. is that you want the derived class objects to be substitutable for the base
  621. class objects.  In the case of Circle/Ellipse, the "setSize(x,y)" method
  622. violates this substitutability.
  623.  
  624. You have three choices: remove the setSize(x,y) method from Ellipse (thus
  625. breaking existing code that uses that method), or allow a Circle to have a
  626. different height than width (an assymetrical circle; hmmm), or drop the
  627. inheritance relationship.  Sorry, but there simply are no other choices (some
  628. people mention that both Circle and Ellipse could be siblings derived from a
  629. third common base class, but that's just a variant of the third option above).
  630.  
  631. Another way to say this is that you have to either make the base class weaker
  632. (in this case, braindamage Ellipse to the point that you can't set its width
  633. and height to different values), or make the derived class stronger (in this
  634. case, empower a Circle with the ability to be both symmetric and, ahem,
  635. assymetric).  Since neither of these is very satisfying in practice, one
  636. normally simply removes the inheritance relationship.  If the inheritance
  637. relationship simply HAS to exist, you often need to remove the mutator methods
  638. (setHeight(y), setWidth(x), and setSize(x,y)).
  639.  
  640. ==============================================================================
  641.  
  642. Q68: But my problem doesn't have anything to do with circles and ellipses, so
  643.    what good is that silly example to me?
  644.  
  645. Ahhh, there's the rub.  You THINK the circle/ellipse example is just a silly
  646. example.  But in reality, YOUR problem is an isomorphism to that example.
  647.  
  648. I don't care what your inheritance problem is, but all (yes all) bad
  649. inheritances boil down to the circle-is-not-a-kind-of-ellipse example.
  650.  
  651. Here's why: Bad inheritances always have a base class with an extra capability
  652. (often an extra method or two) that a derived class can't satisfy.  You've
  653. either got to make the base class weaker, make the derived class stronger, or
  654. eliminate the proposed inheritance relationship.  I've seen lots and lots and
  655. lots of these bad inheritance proposals, and believe me, they all boil down to
  656. the circle/ellipse problem.
  657.  
  658. If you truly understand the circle/ellipse problem, you'll be able to recognize
  659. bad inheritance everywhere.  If you don't understand what's going on with the
  660. circle/ellipse problem, the chances are high that you'll make some very serious
  661. and very expensive inheritance mistakes.
  662.  
  663. ==============================================================================
  664. SUBSECTION 12C: Inheritance -- Access rules
  665. ==============================================================================
  666.  
  667. Q69: Why can't my derived class access "private" things from my base class?
  668.  
  669. To protect you from future changes to the base class.
  670.  
  671. Derived classes do not get access to private members of a base class.  This
  672. effectively "seals off" the derived class from any changes made to the private
  673. members of the base class.
  674.  
  675. ==============================================================================
  676.  
  677. Q70: What's the difference between "public:", "private:", and "protected:"?
  678.  
  679. "Private:" is discussed in the previous section, and "public:" means "anyone
  680. can access it."  The third option, "protected:", makes a member (either data
  681. member or member fn) accessible to subclasses.
  682.  
  683. ==============================================================================
  684.  
  685. Q71: How can I protect subclasses from breaking when I change internal parts?
  686.  
  687. A class has two distinct interfaces for two distinct sets of clients:
  688.  * its "public:" interface serves unrelated classes.
  689.  * its "protected:" interface serves derived classes.
  690.  
  691. Unless you expect all your subclasses to be built by your own team, you should
  692. consider making your base class's bits be "private:", and use "protected:"
  693. inline access functions to access these data.  This way the private bits can
  694. change, but the derived class's code won't break unless you change the
  695. protected access functions.
  696.  
  697. ==============================================================================
  698. SUBSECTION 12D: Inheritance -- Constructors and destructors
  699. ==============================================================================
  700.  
  701. Q72: When my base class's constructor calls a virtual function, why doesn't my
  702.    derived class's override of that virtual function get invoked?
  703.  
  704. During the Base class's constructor, the object isn't yet a Derived, so if
  705. "Base::Base()" calls a virtual function "virt()", the "Base::virt()" will be
  706. invoked, even if "Derived::virt()" exists.
  707.  
  708. Similarly, during Base's destructor, the object is no longer a Derived, so when
  709. Base::~Base() calls "virt()", "Base::virt()" gets control, NOT the
  710. "Derived::virt()" override.
  711.  
  712. You'll quickly see the wisdom of this approach when you imagine the disaster if
  713. "Derived::virt()" touched a member object from the Derived class.
  714.  
  715. ==============================================================================
  716.  
  717. Q73: Does a derived class destructor need to explicitly call the base
  718.    destructor?
  719.  
  720. No, never explicitly call a destructor (where "never" means "rarely").
  721.  
  722. A derived class's destructor (whether or not you explicitly define one)
  723. AUTOMATICALLY invokes the destructors for member objects and base class
  724. subobjects.  Member objects are destroyed in the reverse order they appear
  725. within the class, then base class subobjects are destroyed in the reverse order
  726. that they appear in the class's list of base classes.
  727.  
  728. You should explicitly call a destructor ONLY in esoteric situations, such as
  729. when destroying an object created by the "placement new operator."
  730.  
  731. ==============================================================================
  732. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  733. ==============================================================================
  734.  
  735. Q74: How do you express "private inheritance"?
  736.  
  737. When you use ": private" instead of ": public."  E.g.,
  738.  
  739.     class Foo : private Bar {
  740.       //...
  741.     };
  742.  
  743. ==============================================================================
  744.  
  745. Q75: How are "private inheritance" and "composition" similar?
  746.  
  747. Private inheritance is a syntactic variant of composition (has-a).
  748.  
  749. E.g., the "car has-a engine" relationship can be expressed using composition:
  750.  
  751.     class Engine {
  752.     public:
  753.       Engine(int numCylinders);
  754.       void start();            //starts this Engine
  755.     };
  756.  
  757.     class Car {
  758.     public:
  759.       Car() : e_(8) { }        //initializes this Car with 8 cylinders
  760.       void start() { e_.start(); }    //start this Car by starting its engine
  761.     private:
  762.       Engine e_;
  763.     };
  764.  
  765. The same "has-a" relationship can also be expressed using private inheritance:
  766.  
  767.     class Car : private Engine {
  768.     public:
  769.       Car() : Engine(8) { }        //initializes this Car with 8 cylinders
  770.       Engine::start;        //start this Car by starting its engine
  771.     };
  772.  
  773. There are several similarities between these two forms of composition:
  774.  * in both cases there is exactly one Engine member object contained in a Car.
  775.  * in neither case can users (outsiders) convert a Car* to an Engine*.
  776.  
  777. There are also several distinctions:
  778.  * the first form is needed if you want to contain several Engines per Car.
  779.  * the second form can introduce unnecessary multiple inheritance.
  780.  * the second form allows members of Car to convert a Car* to an Engine*.
  781.  * the second form allows access to the "protected" members of the base class.
  782.  * the second form allows Car to override Engine's virtual functions.
  783.  
  784. Note that private inheritance is usually used to gain access into the
  785. "protected:" members of the base class, but this is usually a short-term
  786. solution (translation: a band-aid; see below).
  787.  
  788. ==============================================================================
  789.  
  790. Q76: Which should I prefer: composition or private inheritance?
  791.  
  792. Composition.
  793.  
  794. Normally you don't WANT to have access to the internals of too many other
  795. classes, and private inheritance gives you some of this extra power (and
  796. responsibility).  But private inheritance isn't evil; it's just more expensive
  797. to maintain, since it increases the probability that someone will change
  798. something that will break your code.
  799.  
  800. A legitimate, long-term use for private inheritance is when you want to build a
  801. class Fred that uses code in a class Wilma, and the code from class Wilma needs
  802. to invoke methods from your new class, Fred.  In this case, Fred calls
  803. non-virtuals in Wilma, and Wilma calls (usually pure) virtuals in itself, which
  804. are overridden by Fred.  This would be much harder to do with composition.
  805.  
  806.     class Wilma {
  807.     protected:
  808.       void fredCallsWilma()
  809.         { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); }
  810.       virtual void wilmaCallsFred() = 0;
  811.     };
  812.  
  813.     class Fred : private Wilma {
  814.     public:
  815.       void barney()
  816.         { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); }
  817.     protected:
  818.       virtual void wilmaCallsFred()
  819.         { cout << "Fred::wilmaCallsFred()\n"; }
  820.     };
  821.  
  822. ==============================================================================
  823.  
  824. Q77: Should I pointer-cast from a "privately" derived class to its base
  825.    class?
  826.  
  827. Generally, No.
  828.  
  829. From a method or friend of a privately derived class, the relationship to the
  830. base class is known, and the upward conversion from PrivatelyDer* to Base* (or
  831. PrivatelyDer& to Base&) is safe; no cast is needed or recommended.
  832.  
  833. However users of PrivateDer should avoid this unsafe conversion, since it is
  834. based on a "private" decision of PrivateDer, and is subject to change without
  835. notice.
  836.  
  837. ==============================================================================
  838.  
  839. Q78: How is protected inheritance related to private inheritance?
  840.  
  841. Similarities: both allow overriding virtuals in the private/protected base
  842. class, neither claims the derived is a kind-of its base.
  843.  
  844. Dissimilarities: protected inheritance allows derived classes of derived
  845. classes to know about the inheritance relationship (it exposes your grand kids
  846. to your implementation details).  This has both benefits (it allows subclasses
  847. of the protected derived class to exploit the relationship to the protected
  848. base class) and costs (the protected derived class can't change the
  849. relationship without potentially breaking further derived classes).
  850.  
  851. Protected inheritance uses the ": protected" syntax:
  852.  
  853.     class Car : protected Engine {
  854.       //...
  855.     };
  856.  
  857. ==============================================================================
  858.  
  859. Q79: What are the access rules with "private" and "protected" inheritance?
  860.  
  861. Take these classes as examples:
  862.  
  863.     class B                    { /*...*/ };
  864.     class D_priv : private   B { /*...*/ };
  865.     class D_prot : protected B { /*...*/ };
  866.     class D_publ : public    B { /*...*/ };
  867.     class UserClass            { B b; /*...*/ };
  868.  
  869. None of the subclasses can access anything that is private in B.  In D_priv,
  870. the public and protected parts of B are "private".  In D_prot, the public and
  871. protected parts of B are "protected".  In D_publ, the public parts of B are
  872. public and the protected parts of B are protected (D_publ is-a-kind-of-a B).
  873. Class "UserClass" can access only the public parts of B, which "seals off"
  874. UserClass from B.
  875.  
  876. To make a public member of B so it is public in D_priv or D_prot, state the
  877. name of the member with a "B::" prefix.  E.g., to make member "B::f(int,float)"
  878. public in D_prot, you would say:
  879.  
  880.     class D_prot : protected B {
  881.     public:
  882.       B::f;    //note: not  "B::f(int,float)"
  883.     };
  884.  
  885. ==============================================================================
  886. SECTION 13: Abstraction
  887. ==============================================================================
  888.  
  889. Q80: What's the big deal of separating interface from implementation?
  890.  
  891. Interfaces are a company's most valuable resources.  Designing an interface
  892. takes longer than whipping together a concrete class which fulfills that
  893. interface.  Furthermore interfaces require the time of more expensive people.
  894.  
  895. Since interfaces are so valuable, they should be protected from being tarnished
  896. by data structures and other implementation artifacts.  Thus you should
  897. separate interface from implementation.
  898.  
  899. ==============================================================================
  900.  
  901. Q81: How do I separate interface from implementation in C++ (like Modula-2)?
  902.  
  903. Use an ABC (see next FAQ).
  904.  
  905. ==============================================================================
  906.  
  907. Q82: What is an ABC ("abstract base class")?
  908.  
  909. At the design level, an ABC corresponds to an abstract concept.  If you asked a
  910. Mechanic if he repaired Vehicles, he'd probably wonder what KIND-OF Vehicle you
  911. had in mind.  Chances are he doesn't repair space shuttles, ocean liners,
  912. bicycles, or nuclear submarines.  The problem is that the term "Vehicle" is an
  913. abstract concept (e.g., you can't build a "vehicle" unless you know what kind
  914. of vehicle to build).  In C++, class Vehicle would be an ABC, with Bicycle,
  915. SpaceShuttle, etc, being subclasses (an OceanLiner is-a-kind-of-a Vehicle).  In
  916. real-world OOP, ABCs show up all over the place.
  917.  
  918. As programming language level, an ABC is a class that has one or more pure
  919. virtual member functions (see next FAQ).  You cannot make an object (instance)
  920. of an ABC.
  921.  
  922. ==============================================================================
  923.  
  924. Q83: What is a "pure virtual" member function?
  925.  
  926. A member function of an ABC that you can implement only in a derived class.
  927.  
  928. Some member functions exist in concept, but can't have any actual defn.  E.g.,
  929. suppose I asked you to draw a Shape at location (x,y) that has size 7.  You'd
  930. ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc,
  931. are drawn differently).  In C++, we indicate the existence of the "draw()"
  932. method, but we recognize it can (logically) be defined only in subclasses:
  933.  
  934.     class Shape {
  935.     public:
  936.       virtual void draw() const = 0;
  937.       //...                     ^^^--- "= 0" means it is "pure virtual"
  938.     };
  939.  
  940. This pure virtual function makes "Shape" an ABC.  If you want, you can think of
  941. the "= 0" syntax as if the code were at the NULL pointer.  Thus "Shape"
  942. promises a service to its users, yet Shape isn't able to provide any code to
  943. fulfill that promise.  This ensures any actual object created from a [concrete]
  944. class derived of Shape *WILL* have the indicated member fn, even though the
  945. base class doesn't have enough information to actually DEFINE it yet.
  946.  
  947. ==============================================================================
  948.  
  949. Q84: How can I provide printing for an entire hierarchy of classes?
  950.  
  951. Provide a friend operator<< that calls a protected virtual function:
  952.  
  953.     class Base {
  954.     public:
  955.       friend ostream& operator<< (ostream& o, const Base& b)
  956.         { b.print(o); return o; }
  957.       //...
  958.     protected:
  959.       virtual void print(ostream& o) const;  //or "=0;" if "Base" is an ABC
  960.     };
  961.  
  962.     class Derived : public Base {
  963.     protected:
  964.       virtual void print(ostream& o) const;
  965.     };
  966.  
  967. Now all subclasses of Base merely provide their own "print(ostream&) const"
  968. member function (they all share the common "<<" operator).  This technique
  969. allows friends to ACT as if they supported dynamic binding.
  970.  
  971. ==============================================================================
  972.  
  973. Q85: When should my destructor be virtual?
  974.  
  975. When you may "delete" a derived object via a base pointer.
  976.  
  977. Virtual fns bind to the code associated with the class of the object, rather
  978. than with the class of the pointer/ref.  When you say "delete basePtr", and the
  979. base class has a virtual destructor, the destructor that gets invoked is the
  980. one associated with the type of the object *basePtr, rather than the one
  981. associated with the type of the pointer.  This is generally A Good Thing.
  982.  
  983. To make life easy for you, the only time you wouldn't want to make a class's
  984. destructor virtual is if that class has NO virtual fns, since the introduction
  985. of the first virtual fn imposes some space overhead in each object (typically
  986. one machine word).  This is how the compiler implements the magic of dynamic
  987. binding; it usually boils down to an extra ptr per object called the "virtual
  988. table pointer" or "vptr".
  989.  
  990. ==============================================================================
  991.  
  992. Q86: What is a "virtual constructor"?
  993.  
  994. An idiom that allows you to do something that C++ doesn't directly support.
  995.  
  996. You can get the effect of virtual constructor by a virtual "createCopy()"
  997. member fn (for copy constructing), or a virtual "createSimilar()" member fn
  998. (for the default constructor).
  999.  
  1000.     class Shape {
  1001.     public:
  1002.       virtual ~Shape() { }        //see on "virtual destructors" for more
  1003.       virtual void draw() = 0;
  1004.       virtual void move() = 0;
  1005.       //...
  1006.       virtual Shape* createCopy() const = 0;
  1007.       virtual Shape* createSimilar() const = 0;
  1008.     };
  1009.  
  1010.     class Circle : public Shape {
  1011.     public:
  1012.       Circle* createCopy()    const { return new Circle(*this); }
  1013.       Circle* createSimilar() const { return new Circle(); }
  1014.       //...
  1015.     };
  1016.  
  1017. The invocation of "Circle(*this)" is that of copy construction ("*this" has
  1018. type "const Circle&" in these methods).  "createSimilar()" is similar, but it
  1019. constructs a "default" Circle.
  1020.  
  1021. Users use these as if they were "virtual constructors":
  1022.  
  1023.     void userCode(Shape& s)
  1024.     {
  1025.       Shape* s2 = s.createCopy();
  1026.       Shape* s3 = s.createSimilar();
  1027.       //...
  1028.       delete s2;    //relies on destructor being virtual!!
  1029.       delete s3;    // ditto
  1030.     }
  1031.  
  1032. This fn will work correctly regardless of whether the Shape is a Circle,
  1033. Square, or some other kind-of Shape that doesn't even exist yet.
  1034.  
  1035. --
  1036. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  1037. Technology consulting services
  1038. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  1039.